import Vue from 'vue'
import Router from 'vue-router'
import store from '../store/index'

const Home = () => import('../views/home/Home')
const Login = () => import('../views/login/Login')
const Register = () => import('../views/register/Register')
const Profile = () => import('../views/profile/Profile')

// 1.通过Vue.use(插件),安装插件
Vue.use(Router)

// 2.创建路由对象

// 配置路由和组件之间的映射关系
const routes = [
    {
        path: '',
        redirect: './home'
    },
    {
        path: '/home',
        component: Home,
        meta: {
            title: '主页',
        }
    },
    {
        path: '/login',
        component: Login,
        meta: {
            title: '登录',
        }
    },
    {
        path: '/register',
        component: Register,
        meta: {
            title: '注册',
        }
    },
    {
        path: '/profile',
        component: Profile,
        meta: {
            title: '用户管理',
        }
    }
];

if (window.localStorage.getItem('loginJudge') === 'true') {
    store.commit('setIsLogin',Boolean(window.localStorage.getItem('loginJudge')));
    store.commit('setUserName', window.localStorage.getItem('userName'));
    store.commit('setPassWord', window.localStorage.getItem('passWord'));
    store.commit('setPhone', window.localStorage.getItem('phone'));
    store.commit('setGender', window.localStorage.getItem('gender'));
    store.commit('setAge', window.localStorage.getItem('age'));
    store.commit('setEmail', window.localStorage.getItem('email'));
    store.commit('setStatus', window.localStorage.getItem('status'));
    store.commit('setUid', window.localStorage.getItem('uid'));
}

const router = new Router({
    routes,
    mode: 'hash'
});

// 全局导航守卫
router.beforeEach((to, from, next) => {
    if(store.getters.isLogin === true) {
        // eslint-disable-next-line no-console
        console.log(store.getters.isLogin);
        if (to.path === '/login' || to.path === '/register') {
            //在已经登录状态下，访问Login.vue页面 会跳到Home.vue
            document.title = to.matched[0].meta.title;
            next({
                path: '/home'
            });
        }else {
            document.title = to.matched[0].meta.title;
            next();
        }
    }else {
        if (to.path === '/login' || to.path === '/register' || to.path === '/home') {  // 如果是登录页面的话，直接next()
            document.title = to.matched[0].meta.title;
            next();
        }else {
            // 否则 跳转到登录页面
            next({
                path: '/login'
            });
            alert("你必须先登录")
        }
    }
});

// 3.将router对象传入到Vue实例
export default router